package by.averianov.discounta.webapp.page.loginpage;

import javax.inject.Inject;
import javax.persistence.NoResultException;

import org.apache.wicket.Application;
import org.apache.wicket.Page;
import org.apache.wicket.authroles.authentication.AuthenticatedWebSession;
import org.apache.wicket.extensions.ajax.markup.html.modal.ModalWindow.PageCreator;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.PasswordTextField;
import org.apache.wicket.markup.html.form.RequiredTextField;
import org.apache.wicket.markup.html.link.Link;
import org.apache.wicket.model.CompoundPropertyModel;
import org.apache.wicket.model.ResourceModel;
import org.apache.wicket.request.mapper.parameter.PageParameters;
import org.apache.wicket.util.string.StringValue;
import org.apache.wicket.util.string.Strings;

import by.averianov.discounta.datamodel.UserAccount;
import by.averianov.discounta.datamodel.UserProfile;
import by.averianov.discounta.services.UserService;
import by.averianov.discounta.webapp.page.BaseLayout;
import by.averianov.discounta.webapp.page.homepage.HomePage;
import by.averianov.discounta.webapp.page.loginpage.loginactivate.LoginActivatePage;

public class LoginPage extends BaseLayout {	

	private PageParameters pageParameters = new PageParameters();
	
	public static final String ID_FORM = "form";
	public static final String ID_PASSWORD = "password";
	public static final String ID_USERNAME = "username";

	private String username;
	private String password;
	
	public LoginPage(PageParameters pageParameters) {
		super(pageParameters);
		super.currentMenu = "menuLogin";
		if(pageParameters != null) {
			this.pageParameters = pageParameters;
		}
	}
		
	@Inject
	private UserService userService;

	@Override
	protected void onInitialize() {
		super.onInitialize();
		
		StringValue userProfileId = pageParameters.get(0);
		StringValue activationCode = pageParameters.get(1);
		try {
			UserProfile currentUserProfile = userService.getUserProfile(Long.parseLong(userProfileId.toString()));
		
			if(!userService.getUserAccount(currentUserProfile.getId()).getUserStatus() 
					|| userService.getUserAccount(currentUserProfile.getId()).getActivateCode() == activationCode.toString()) {
				UserAccount currentUserAccount = userService.getUserAccount(currentUserProfile.getId());
				currentUserAccount.setUserStatus(true);
				userService.saveOrUpdateUser(currentUserProfile, currentUserAccount);
				info(new ResourceModel("p.login.useractivate").getObject());
			} else {
				HomePage page = new HomePage();
				page.error(new ResourceModel("p.error.linkisnotvalid").getObject());
				setResponsePage(page);
			}
		} catch (NumberFormatException e) {
			//
		}
		
		final Form<Void> form = new Form<Void>(ID_FORM) {

			@Override
			protected void onSubmit() {
				if (Strings.isEmpty(username) || Strings.isEmpty(password)) {
					return;
				}
				Page page = new LoginPage(pageParameters);
				try {
					boolean userStatus = userService.getAccountByEmail(username).getUserStatus();
					
					if (userStatus) {
						final boolean authResult = AuthenticatedWebSession.get().signIn(username, password);
						if (authResult) {
							page = new HomePage();
							
						} else {
							page.error(new ResourceModel("p.error.loginpassword").getObject());
						}
					} else {
						UserAccount account = userService.getAccountByEmail(username);
						UserProfile profile = userService.getUserProfile(account.getId());
						page = new LoginActivatePage(account ,profile, new PageCreator() {

							@Override
							public Page createPage() {
								return new LoginPage(pageParameters);
							}
						});
						
					}
				} catch (NoResultException e) {
					page.error(new ResourceModel("p.error.nouser").getObject());					
				}
				setResponsePage(page);
			}
		};

		form.add(new Label("Enter", getButtonEnter()));
				
		Link linkCancel = new Link("linkCancel"){
			@Override
			public void onClick() {
				setResponsePage(new HomePage());
			}
		};
		linkCancel.add(new Label("labelCancel", getButtonCancel()));
		form.add(linkCancel);
		
		form.setDefaultModel(new CompoundPropertyModel<LoginPage>(this));
		form.add(new RequiredTextField<String>(ID_USERNAME));
		form.add(new PasswordTextField(ID_PASSWORD));
		add(form);
	}

}
